﻿using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

public class StringTool
{
    /// <summary>
    /// 给字符串添加 html文本颜色
    /// </summary>
    /// <param name="str">源字符串</param>
    /// <param name="color">颜色</param>
    public static string AddHtmlColorStr(string str, Color color)
    {
        string ColorStr = NGUIText.EncodeColor(color);
        return string.Format("[{0}]{1}[-]", ColorStr, str);
    }

    /// <summary>
    /// 给字符串添加html文本点击 属性
    /// </summary>
    /// <param name="str">原字符串</param>
    /// <param name="url">要给字符串点击添加的属性</param>
    public static string AddHtmlUrlStr(string str, string url)
    {
        return string.Format("[url={0}]{1}[/url]", url, str);
    }

    public static string UTF8ToBase64(string str)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(str);
        return Convert.ToBase64String(bytes);
    }

    public static string Base64ToUTF8(string str)
    {
        byte[] outPut = Convert.FromBase64String(str);
        return Encoding.UTF8.GetString(outPut);
    }

    public static string GetStringMD5(string str)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(str);
        byte[] md5 = MD5.Create().ComputeHash(bytes);
        StringBuilder sBuilder = new StringBuilder();

        for (int i = 0; i < md5.Length; i++)
        {
            sBuilder.Append(md5[i].ToString("x"));
        }
        return sBuilder.ToString();
    }
    
    public static bool IsNumber(string str)
    {
        if (string.IsNullOrEmpty(str)) { return false; }
        for (int i = 0; i < str.Length; i++)
        {
            if (!Char.IsNumber(str[i])) { return false; }
        }
        return true;
    }

    /// <summary>
    /// 字符串替换 替换第一个匹配的项    和 string.Replace 不同
    /// </summary>
    /// <param name="str"></param>
    /// <param name="oldString"></param>
    /// <param name="newString"></param>
    public static string EReplace(string str, string oldString, string newString)
    {
        int index = str.IndexOf(oldString);
        if (index != -1)
        {
            str = str.Remove(index, oldString.Length);
            str = str.Insert(index, newString);
        }
        return str;
    }
    
    public static string GetDateTimeString(DateTime dTime)
    {
        object[] args = { dTime.Year, dTime.Month, dTime.Day, dTime.Hour, dTime.Minute, dTime.Second };
        return string.Format("{0}/{1}/{2}/{3}:{4}:{5}", args);
    }
}